<template>
	<view class="appointment-container">
		<!-- 页面标题 -->
		<view class="page-title">选择预约时段</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<view class="loading-icon">加载中...</view>
		</view>

		<!-- 错误提示 -->
		<view v-if="errorMsg" class="error-message">
			{{ errorMsg }}
		</view>

		<!-- 预约时段列表 -->
		<view v-else class="time-list">
			<view class="time-items">
				<!-- 循环展示预约时段 -->
				<view v-for="(item, index) in appointments" :key="item.appointmentId"
					:class="['time-item', item.appointmentStatus === 0 ? 'available' : 'reserved']">

					<view class="date-text">{{ formatDate(item.appointmentTime) }}</view>
					<view class="time-text">时间: {{ formatTime(item.appointmentTime) }}</view>
					<view class="duration-text">时长: {{ item.appointmentDuration }}分钟</view>

					<!-- 状态标签 -->
					<view class="status-tag">
						{{ item.appointmentStatus === 0 ? '可预约' : '已预约' }}
					</view>

					<!-- 预约按钮（仅可预约状态显示） -->
					<view v-if="item.appointmentStatus === 0" class="reserve-btn" @click="handleAppointment(item)">
						立即预约
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="appointments.length === 0" class="empty-state">
				<view class="empty-icon">暂无可用预约时段</view>
			</view>
		</view>

		<!-- 预约成功弹窗 -->
		<view v-if="showSuccessModal" class="modal-mask" @click="closeModal">
			<!-- 阻止弹窗内容点击事件冒泡 -->
			<view class="modal-content" @click.stop>
				<view class="modal-icon">✓</view>
				<view class="modal-title">预约成功</view>
				<view class="modal-desc">请在10分钟内完成支付，超时将自动取消</view>
				<!-- 去支付按钮 -->
				<view v-show="showFlag" class="modal-btn" @click="goToPayment">
					去支付
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		queryAppointment,
		createAppointment
	} from '@/api/appointment';

	export default {
		data() {
			return {
				showFlag: false,
				doctorId: null,
				appointments: [],
				loading: true,
				showSuccessModal: false,
				currentAppointmentId: null,
				errorMsg: ''
			};
		},
		onLoad(option) {
			if (option.doctorId) {
				this.doctorId = parseInt(option.doctorId);
				this.fetchAppointments();
			} else {
				uni.navigateBack();
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
			}
		},
		methods: {
			async fetchAppointments() {
				try {
					const res = await queryAppointment({
						doctorId: this.doctorId
					});
					if (res.code === 200 && res.data) {
						this.appointments = res.data.sort((a, b) =>
							new Date(a.appointmentTime) - new Date(b.appointmentTime)
						);
						this.errorMsg = '';
					} else {
						this.errorMsg = res.msg || '获取预约数据失败';
					}
				} catch (error) {
					console.error('获取预约数据失败', error);
					this.errorMsg = '获取预约时段失败，请稍后重试';
					uni.showToast({
						title: this.errorMsg,
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			async handleAppointment(item) {
				console.log('点击预约按钮，item:', item); // 添加日志输出
				// 验证状态
				console.log('预约状态:', item.appointmentStatus);
				if (item.appointmentStatus !== 0) return;

				// 验证用户信息
				const userId = this.$store.state.userId;
				console.log('用户ID:', this.$store.state.userId);
				if (!userId) {
					uni.showToast({
						title: '未获取到用户信息，请重新登录',
						icon: 'none'
					});
					return;
				}

				// 验证预约ID
				if (!item.appointmentId) {
					uni.showToast({
						title: '预约信息异常',
						icon: 'none'
					});
					return;
				}

				// 执行预约
				uni.showLoading({
					title: '预约中...'
				});
				try {
					const response = await createAppointment({
						appointmentId: item.appointmentId,
						userId: userId
					});
					// 处理响应，打印结果
					console.log('创建预约请求结果:', response);
					uni.hideLoading();
					if (response.code === 1) {
						// 确保预约ID正确设置
						this.currentAppointmentId = item.appointmentId;
						console.log('预约成功，ID为：', this.currentAppointmentId);
						this.showFlag = true;

						// 强制更新UI显示弹窗
						this.$nextTick(() => {
							this.showSuccessModal = true;
							console.log('弹窗已显示，showSuccessModal:', this.showSuccessModal);
						});

						// 更新本地状态
						const index = this.appointments.findIndex(app => app.appointmentId === item.appointmentId);
						if (index !== -1) {
							this.appointments = [
								...this.appointments.slice(0, index),
								{
									...this.appointments[index],
									appointmentStatus: 1
								},
								...this.appointments.slice(index + 1)
							];
						}
					} else {
						uni.showToast({
							title: response.msg || '预约失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('预约失败', error);
					uni.showToast({
						title: '预约失败，请重试',
						icon: 'none'
					});
				}
			},

			// 跳转到支付页面
			goToPayment() {
				console.log('点击去支付，当前预约ID:', this.currentAppointmentId);
				this.showSuccessModal = false;

				// 确保 currentAppointmentId 不为空
				if (!this.currentAppointmentId) {
					uni.showToast({
						title: '缺少预约ID，无法跳转',
						icon: 'none'
					});
					return;
				}

				const url = `/pages/appointment/payappointment?appointmentId=${this.currentAppointmentId}`;
				console.log('跳转支付页面路径：', url);
				uni.navigateTo({
					url: url,
					fail: (err) => {
						console.error('支付页面跳转失败：', err);
						uni.reLaunch({
							url: url,
							fail: (err2) => {
								console.error('reLaunch也失败：', err2);
								uni.showToast({
									title: '跳转支付页面失败',
									icon: 'none'
								});
							}
						});
					}
				});
			},

			// 关闭弹窗方法
			closeModal() {
				this.showSuccessModal = false;
			},

			formatDate(timeStr) {
				const date = new Date(timeStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				return `${year}-${month}-${day} ${weekDays[date.getDay()]}`;
			},

			formatTime(timeStr) {
				return timeStr.split(' ')[1].slice(0, 5);
			}
		}
	};
</script>

<style scoped>
	/* 原有样式保持不变，增加以下样式确保弹窗显示 */
	/* 确保弹窗遮罩层覆盖整个屏幕 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
		/* 提高层级确保显示在最上层 */
	}

	/* 弹窗内容样式强化 */
	.modal-content {
		width: 500rpx;
		background-color: #fff;
		border-radius: 15rpx;
		text-align: center;
		padding: 50rpx 30rpx;
		/* 增加阴影和动画效果 */
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
		animation: modalIn 0.3s ease-out;
	}

	/* 去支付按钮样式强化 */
	.modal-btn {
		background-color: #36cbcb;
		color: #fff;
		font-size: 30rpx;
		padding: 15rpx 0;
		border-radius: 50rpx;
		/* 增加交互反馈 */
		transition: background-color 0.2s;
		cursor: pointer;
	}

	.modal-btn:active {
		background-color: #2aa8a8;
	}

	/* 弹窗进入动画 */
	@keyframes modalIn {
		from {
			opacity: 0;
			transform: scale(0.9);
		}

		to {
			opacity: 1;
			transform: scale(1);
		}
	}

	/* 其他原有样式... */
	.appointment-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 50rpx;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		text-align: center;
		padding: 30rpx 0;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.loading {
		text-align: center;
		padding: 100rpx 0;
		color: #666;
	}

	.loading-icon {
		font-size: 28rpx;
	}

	.error-message {
		text-align: center;
		padding: 20rpx;
		color: #f53f3f;
		font-size: 28rpx;
		background-color: #fff1f0;
		margin: 15rpx;
		border-radius: 8rpx;
	}

	.time-list {
		margin: 15rpx;
	}

	.time-items {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.time-item {
		width: 345rpx;
		background-color: #fff;
		border-radius: 8rpx;
		padding: 20rpx;
		position: relative;
		min-height: 180rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		transition: all 0.2s;
	}

	.time-item.available {
		border: 1px solid #36cbcb;
	}

	.time-item.available:active {
		background-color: #f0fcf9;
	}

	.time-item.reserved {
		border: 1px solid #ddd;
		background-color: #f9f9f9;
	}

	.date-text {
		font-size: 26rpx;
		color: #333;
		line-height: 1.4;
	}

	.time-text {
		font-size: 28rpx;
		color: #333;
		margin-top: 8rpx;
	}

	.duration-text {
		font-size: 26rpx;
		color: #666;
		margin-top: 8rpx;
	}

	.status-tag {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		font-size: 24rpx;
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
	}

	.time-item.available .status-tag {
		background-color: #e6f7f0;
		color: #36cbcb;
	}

	.time-item.reserved .status-tag {
		background-color: #f5f5f5;
		color: #999;
	}

	.reserve-btn {
		margin-top: 15rpx;
		background-color: #36cbcb;
		color: #fff;
		font-size: 26rpx;
		text-align: center;
		padding: 10rpx 0;
		border-radius: 5rpx;
		width: 100%;
		align-self: flex-end;
	}

	.empty-state {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	.modal-icon {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50rpx;
		background-color: #4cd964;
		color: #fff;
		font-size: 60rpx;
		line-height: 100rpx;
		margin: 0 auto 30rpx;
	}

	.modal-title {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.modal-desc {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 40rpx;
	}

	@media (max-width: 375rpx) {
		.time-item {
			width: 100%;
		}
	}
</style>